package com.ktvme.service.impl;



import com.ktvme.constant.StatusConstant;
import com.ktvme.dto.UserDTO;
import com.ktvme.dto.UserLoginDTO;
import com.ktvme.entity.User;
import com.ktvme.exception.AccountLockedException;
import com.ktvme.exception.AccountNotFoundException;
import com.ktvme.exception.PasswordErrorException;
import com.ktvme.mapper.UserMapper;
import com.ktvme.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public void save(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        log.info("新增用户：{}",userDTO);
        user.setStatus(StatusConstant.ENABLE);
        userMapper.insert(user);
    }

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);
        log.info("根据用户名查询到的用户信息为：{}",user);
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException("账号不存在");
        }
        password = DigestUtils.md5DigestAsHex((password).getBytes());
        //密码比对
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException("密码错误");
        }

        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException("账号被锁定");
        }

        //3、返回实体对象
        return user;
    }
}
